<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Logic;

use App\Model\Article;
use App\Model\ArticleCollect;
use App\Model\ArticlePraise;
use App\Model\Category;
use Exception;

class ArticleLogic
{
    /**
     * 头条首页数据
     * @return array
     */
    public static function getHomepageData(): array
    {
        $columns = self::getCategoryList();
        //推荐图文
        $res = Article::query()->where([['is_recommend', '=', 1], ['thumb', '<>', '']])->with(['author', 'category'])->orderBy('id', 'desc')->limit(3)->get()->toArray();
        $headlines = [];
        foreach ($res as $r) {
            $headlines[] = self::formatArticle($r);
        }
        unset($res);
        return [
            'bannerList' => [],
            'columnList' => array_values($columns),
            'headlines' => $headlines,
            'matchBasicInfo' => null
        ];
    }

    /**
     * 获取分类列表.
     */
    public static function getCategoryList(): array
    {
        return Category::query()->where('parentid', 0)->orderBy('listorder')->get(['id', 'catname'])->keyBy('id')->toArray();
    }

    /**
     * @throws Exception
     */
    public static function getDetail($userid, $id): array
    {
        $article = Article::query()->where('id', $id)->with(['category', 'author', 'content'])->first();
        if (!$article) {
            throw new Exception('资讯不存在');
        }
        $detail = self::formatArticle($article->toArray());
        if ($userid) {
            $detail['isPraise'] = ArticlePraise::query()->where(['userid' => $userid, 'aid' => $id])->exists() ? 1 : 0;
            $detail['isCollect'] = ArticleCollect::query()->where(['userid' => $userid, 'aid' => $id])->exists() ? 1 : 0;
        } else {
            $detail['isPraise'] = $detail['isCollect'] = 0;
        }
        Article::query()->where('id', $id)->increment('hits');
        $detail['readCount']++;
        return $detail;
    }

    /**
     * 获取资讯列表.
     * @param mixed $input
     */
    public static function getArticleList($input): array
    {
        [, $pageSize, $offset] = parsePageParams($input);
        $where = [];
        if (isset($input['query']['columnId']) && intval($input['query']['columnId'])) {
            $where[] = ['catid', '=', (int)$input['query']['columnId']];
        }
        if (isset($input['query']['authorId']) && intval($input['query']['authorId'])) {
            $where[] = ['author_id', '=', (int)$input['query']['authorId']];
        }
        if (isset($input['query']['isRecommend']) && intval($input['query']['isRecommend'])) {
            $where[] = ['is_recommend', '=', 1];
        }
        if (isset($input['query']['thumb']) && intval($input['query']['thumb'])) {
            $where[] = ['thumb', '<>', ''];
        }
        $total = Article::query()->where($where)->count();
        if ($total) {
            $order = isset($input['sort']) && $input['sort'] == 'hits' ? 'hits' : 'id';
            $rs = Article::query()->where($where)->with(['author', 'category'])->offset($offset)->limit($pageSize)->orderBy($order, 'desc')->get()->toArray();
            $records = [];
            foreach ($rs as $r) {
                $records[] = self::formatArticle($r);
            }
        }
        return [
            'total' => $total,
            'pages' => ceil($total / $pageSize),
            'records' => $records ?? [],
        ];
    }

    /**
     * 喜欢
     * @param $userId
     * @param $articleId
     * @return true
     * @throws Exception
     */
    public static function praise($userId, $articleId): true
    {
        if (!Article::query()->where('id', $articleId)->exists()) {
            throw new Exception('文章不存在');
        }
        $info = ArticlePraise::query()->where(['userid' => $userId, 'aid' => $articleId])->first();
        if ($info) {
            ArticlePraise::query()->where('id', $info['id'])->delete();
            Article::query()->where([['id', '=', $articleId], ['praise', '>', 0]])->decrement('praise');
        } else {
            ArticlePraise::create([
                'userid' => $userId,
                'aid' => $articleId,
                'add_time' => time()
            ]);
            Article::query()->where('id', $articleId)->increment('praise');
        }
        return true;
    }

    /**
     * 收藏
     * @param $userId
     * @param $articleId
     * @return true
     * @throws Exception
     */
    public static function collect($userId, $articleId): true
    {
        if (!Article::query()->where('id', $articleId)->exists()) {
            throw new Exception('文章不存在');
        }
        $info = ArticleCollect::query()->where(['userid' => $userId, 'aid' => $articleId])->first();
        if ($info) {
            ArticleCollect::query()->where('id', $info['id'])->delete();
            Article::query()->where([['id', '=', $articleId], ['collect', '>', 0]])->decrement('collect');
        } else {
            ArticleCollect::create([
                'userid' => $userId,
                'aid' => $articleId,
                'add_time' => time()
            ]);
            Article::query()->where('id', $articleId)->increment('collect');
        }
        return true;
    }

    /**
     * 格式化文章
     * @param $info
     * @return array
     */
    public static function formatArticle($info): array
    {
        $return = [
            'id' => $info['id'],
            'title' => $info['title'],
            'columnName' => $info['columnName'] ?? ($info['category']['catname'] ?? ''),
            'columnId' => $info['catid'],
            'image' => $info['thumb'],
            'imageList' => new_json_decode($info['image_list']),
            'praiseCount' => $info['praise'],
            'readCount' => $info['hits'],
            'collectCount' => $info['collect'],
            'timestamp' => $info['add_time'],
            'authorName' => $info['author']['name'] ?? '',
            'authorPic' => $info['author']['avatar'] ?? '',
            'description' => $info['description'],
            'authorDesc' => date('Y年m月d日 h:i:s', $info['add_time']) . ' ' . ($info['author']['name'] ?? '')
        ];
        if (isset($info['content']) && is_array($info['content'])) {
            $return['content'] = $info['content']['content'];
        }
        return $return;
    }
}
